<?php
namespace Model;
use DB;

class Queue extends \Model {
	public static function get_queue($user_id, $per_page = 100, $offset = 0) {
		$query = DB::select()->from('queue');
		if ($user_id != 0) {
			$query->where('user_id', '=', $user_id);      
		}
		$query->order_by('id', 'desc');
		$query->limit($per_page);
		$query->offset($offset);
		$r = $query->execute();
		return $r->as_array();
	} 

	public static function get_cnt($user_id) {
		$query = DB::select()->from('queue');
		$query->where('user_id', '=', $user_id);      
		$r = $query->execute();
		return count($r->as_array());
	}

	public static function add($msg) {
		$data = $msg;
		$query = DB::select()->from('queue');
		$query->where('screen_name', '=', $data['screen_name']);      
		$query->and_where('text', '=', $data['text']);      
		$query->and_where('image', '=', $data['image']);      
		$query->and_where('status', '=', 0);      
		$r = $query->execute();
		if (count($r->as_array()) > 0) return true;

		DB::insert('queue')->set($data)->execute();
	}

	public static function update($msg) {
		$data = $msg;
		if (!$data) return;
		$query = DB::update('queue');
		$query->where('id', '=', $data['id']);      
		$query->set($data)->execute();
	}

	public static function stat() {
		$map  = array(
			'to_send' => 0,
			'sent' => 1,
			'failed' => 2,
			'cancel' => 3,
			'del' => 4
		);
		foreach ($map as $k => $v) {
			$query = DB::select('*')->from('queue');
			$query->where('status', '=', $v);
			$result = $query->execute();
			$r[$k]['total'] = count($result);

			$query = DB::select('*')->from('queue');
			$query->where('status', '=', $v);
			$query->and_where('post_time', '<=', date('Y-m-d 23:59:59', time() + 8 * 60 * 60));
			$query->and_where('post_time', '>=', date('Y-m-d 00:00:01', time() + 8 * 60 * 60));
			$result = $query->execute();
			$r[$k]['today'] = count($result);
		}
		return $r;
	}
}
